<template>
  <a-modal
    v-model:visible="visible"
    draggable
    width="40%"
    @before-ok="handleBeforeOk"
    @cancel="handleChangeVisible"
  >
    <template #title> {{ title }}</template>
    <a-table
      v-model:selectedKeys="selectedKeys"
      row-key="id"
      :scroll="scroll"
      :loading="loading"
      :data="renderData"
      :row-selection="rowSelection"
      :bordered="false"
      :pagination="{
        current: pagination.page,
        total: pagination.total,
        pageSize: pagination.rows,
        showTotal: true,
        showPageSize: true,
      }"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
    >
      <template #columns>
        <a-table-column title="用户组名称" data-index="name" />
      </template>
    </a-table>
  </a-modal>
</template>

<script lang="ts" setup>
  import { TableRowSelection } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { ref, reactive, computed } from 'vue';
  import {
    selectPageUserGroup,
    UserGroupListParams,
    UserGroupVo,
  } from '@/api/user-group';

  const generateFormModel = () => {
    return {
      name: '',
      organizationId: '',
      organizationName: '',
    };
  };
  const pagination = reactive({
    page: 1,
    rows: 20,
    total: 0,
  });
  const scroll = {
    y: 300,
  };
  const selectedKeys = ref<string[]>([]);
  const props = defineProps({
    title: {
      type: String,
      default: '选择用户组',
    },
    multiple: {
      type: Boolean,
    },
  });

  const rowSelection = computed<TableRowSelection>(() => {
    return {
      type: props.multiple ? 'checkbox' : 'radio',
      showCheckedAll: true,
      onlyCurrent: false,
    };
  });

  const { loading, setLoading } = useLoading();
  const renderData = ref<UserGroupVo[]>([]);
  const renderDataAll = ref<UserGroupVo[]>([]);
  const formModel = ref(generateFormModel());
  const visible = ref(false);
  const emit = defineEmits(['change']);

  const fetchData = async (
    params: UserGroupListParams = { ...formModel.value, ...pagination }
  ) => {
    setLoading(true);
    try {
      const { data } = await selectPageUserGroup(params);
      renderData.value = data.rows;
      pagination.total = data.total;
      const arr = new Set([...renderDataAll.value, ...data.rows]);
      renderDataAll.value = [...arr];
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    pagination.page = 1;
    fetchData();
  };
  const onPageChange = (current: number) => {
    pagination.page = current;
    fetchData();
  };
  const onPageSizeChange = (current: number) => {
    pagination.rows = current;
    fetchData();
  };

  function handleChangeVisible(list?: Array<UserGroupVo>) {
    visible.value = !visible.value;
    if (visible.value) {
      search();
      selectedKeys.value = list ? list.map((item) => item.id) : [];
    } else {
      selectedKeys.value = [];
      renderDataAll.value = [];
    }
  }
  function handleBeforeOk(done: any) {
    done(false);
    console.log(
      selectedKeys.value,
      renderDataAll.value.filter((item: any) =>
        selectedKeys.value.includes(item.id)
      )
    );
    emit(
      'change',
      props.multiple
        ? renderDataAll.value.filter((item: any) =>
            selectedKeys.value.includes(item.id)
          )
        : renderDataAll.value.find(
            (item: any) => item.id === selectedKeys.value
          )
    );
    handleChangeVisible();
  }

  defineExpose({ handleChangeVisible });
</script>

<script lang="ts">
  export default {
    name: 'SelectUserGroup',
  };
</script>

<style scoped></style>
